/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.runtime.component
{
	import com.string.StrUnit;
	import com.string.XMLUnit;
	
	import mx.collections.XMLListCollection;
	import mx.controls.treeClasses.DefaultDataDescriptor;

	/**
	 * 树结构的二维表 
	 * 
	 */
	public class EDIDataTree extends XMLListCollection
	{
		
		private var _dataTable:EDIDataTable;
		private var _delIndex:int=-1;
		private var _addDataTableSource:XML=null;
		
		private var _pidField:String="";
		private var _idField:String="";
		private var _rootValue:String="";
		private var _labelField:String="";
		
		private var xTree:XML;
		/**
		 * 排序字段 
		 */		
		public var orderByField:String;
		/**
		 * 排序方式 
		 */		
		public var desc:Boolean=false;
		
		/**
		 * 构造一个树结构的二维表格 
		 * @param dataTable 数据源，即表
		 * @param idField 与pidfield对应的编号
		 * @param pidField 父编号
		 * @param rootValue 根值
		 * @param labelField 显示字段
		 * @param orderByField 排序用字段
		 * @param desc 排序方式。
		 * 
		 */		
		public function EDIDataTree(dataTable:EDIDataTable,idField:String="",pidField:String="",rootValue:String="",
			labelField:String="",orderByField:String="",desc:Boolean=false)
		{
			dataTable.autoCommit = false;
			this._dataTable = dataTable;
			
			this._pidField = pidField;
			this._idField = idField;
			this._rootValue = rootValue;
			this._labelField = labelField;
			this.orderByField=orderByField;
			this.desc=desc;
			
			if(dataTable.source!=null)
			{
				xTree=new XML(<tree />);
				refreshDataTree();
			}
		}
		

		private function xmlToTreeNode(tree:XML,dataSource:XMLList,idField:String,pidField:String,rootValue:String,labelField:String):void
		{
			var treeNode:XML;
			var i:int=0;
			var idValue:String;
			
			while(i<dataSource.length())
			{
				if(dataSource[i][pidField].toString()==rootValue)
				{
					idValue=dataSource[i][idField].toString();
					treeNode=new XML("<tree "+labelField+"=\""+StrUnit.replaceRevert(dataSource[i][labelField].toString())+"\" idValue=\""+ idValue +"\" pidValue=\""+dataSource[i][pidField].toString()+"\" /> "); 
					EDIApplication.outputDebug("treeNode: "+treeNode.toString());
					delete dataSource[i]; //删除该节点
					i=-1;
					xmlToTreeNode(treeNode,dataSource,idField,pidField,idValue,labelField);
					tree.appendChild(treeNode);
				}
				i++;
			}
			EDIApplication.outputDebug("tree: "+tree.toString());
		}
		
		/**
		 * 将根据所选节点输入对应的DataTable行
		 * @param item 所选节点项
		 * @return 
		 * 
		 */		
		public function getDataTableItem(item:Object):Object
		{
			var retObj:Object;
			if(item!=null && item is XML && (item as XML).hasOwnProperty("@idValue"))
			{
				var idvalue:String=item["@idValue"]
				for(var i:int=0;i<this._dataTable.length;i++)
				{
					if(_dataTable[i][_idField]==idvalue)
					{
						retObj=_dataTable[i];
						break;
					}
				}
			}
			return retObj;
		}
		
		/**
		 * 添加新行 
		 * @param item 要添加的新行
		 * @param index 添加到得索引位置
		 * 
		 */		
		override public function addItemAt(item:Object, index:int):void
		{
			this._dataTable.addItem(item);
			refreshDataTree();
		}
		
		/**
		 * 删除指定的行 
		 * @param index 要删除的行索引
		 * @return 
		 * 
		 */		
		override public function removeItemAt(index:int):Object
		{
			if(index<0){return null;}
			if(index==0)
			{
				this.removeAll();
			}
			return null;
		}
		
		/*
		//根据编号删除
		private function deleteItem(index:int,value:XMLList):void
		{
			var retObj:Object=null;
			var iCount:int=value.length();
			for(var i:int=0;i<iCount;i++)
			{
				_delIndex++;
				if(index==_delIndex)
				{
					this._dataTable.removeItemAt(index);					
					delete value[i];
					break;
				}
				else
				{
					deleteItem(index,(value[i] as XML).children());
				}
			}
		}
		*/
		
		
		/**
		 * 删除所有记录 
		 * 
		 */		
		override public function removeAll():void
		{
			super.removeAll();
			_dataTable.removeAll();					
		}
		
		/**
		 * 自动提交 
		 * @param listenerResult 提交成功后的回调函数
		 * @param listenerFault 提交失败后的回调函数
		 * 
		 */		
		public function commitToServer(listenerResult:Function=null,listenerFault:Function=null):void 
		{
			this._dataTable.commitToServer(listenerResult,listenerFault);
		}
		
		/**
		 * 获得 当前ITEM 在dataTable中的索引
		 * @param item 要获得的itemd
		 * @return 
		 * 
		 */		
		public function getDataTableIndex(item:Object):int
		{
			var index:int=-1;
			if(item!=null && item is XML && (item as XML).hasOwnProperty("@idValue"))
			{
				var idvalue:String=item["@idValue"]
				for(var i:int=0;i<this._dataTable.length;i++)
				{
					if(_dataTable[i][_idField]==idvalue)
					{
						_dataTable.cursorIndex=i;
						index=i;
						break;
					}
				}
			}
			return i;	
		}
		
		//
		/**
		 * 删除某节点
		 * @param item 要删除的节点
		 * 
		 */		
		public function removeItem(item:Object):void
		{
			if(item!=null && item is XML && (item as XML).hasOwnProperty("@idValue"))
			{
				var id:String=(item as XML)["@idValue"];
				var xmlSource:XML=new XML(<db />);
				searchItemForIDDown(id,xmlSource,_dataTable.source.copy());
				var xmlList:XMLList=xmlSource.children();
				var iCount:int=xmlList.length();
				var j:int;
				for(j=0;j<this._dataTable.length;j++)
				{
					if(id==_dataTable[j][_idField].toString())
					{
						_dataTable.removeItemAt(j);
						break;
					}
				}
				for(var i:int=0;i<iCount;i++)
				{
					for(j=0;j<this._dataTable.length;j++)
					{
						if(xmlList[i][_idField].toString()==_dataTable[j][_idField].toString())
						{
							_dataTable.removeItemAt(j);
							break;
						}
					}
				}
				new DefaultDataDescriptor().removeChildAt((item as XML).parent(),(item as XML),(item as XML).childIndex());
			}
		}
		
		/**
		 * 根据所选项生成QPath表
		 * @param item 所选项
		 * @return 
		 * 
		 */		
		public function treeNodeToQItem(item:Object):Object
		{
			var xmlSource:XML=new XML(<db />);
			if(item is XML && (item as XML).hasOwnProperty("@idValue"))
			{
				var id:String=(item as XML)["@idValue"];
				searchItemForIDUP(id,xmlSource,_dataTable.source.copy());
				searchItemForIDDown(id,xmlSource,_dataTable.source.copy());
			}
			return new XML(<obj>
				<dataTable>{xmlSource}</dataTable>
			</obj>);
		}
		
		/**
		 * 根据IDFiled内的值向上查找树结构 
		 * @param id
		 * @param xmlSource
		 * @param objSource
		 * 
		 */		
		private function searchItemForIDUP(id:String,xmlSource:XML,objSource:XMLList):void
		{
			if(id!=this._rootValue)
			{
				var i:int=0;
				var idValue:String;
				while(i<objSource.length())
				{
					if(objSource[i][_idField].toString()==id)
					{
						var xml:XML=(objSource[i] as XML).copy();
						idValue=objSource[i][_pidField].toString();
						delete objSource[i]
						searchItemForIDUP(idValue,xmlSource,objSource);
						i=-1;
						xmlSource.appendChild(xml);
						break;
					}
					i++;
				}
			}
		}
		
		/**
		 *  根据IDFiled内的值向下查找树结构
		 * @param id
		 * @param xmlSource
		 * @param objSource
		 * 
		 */		
		private function searchItemForIDDown(id:String,xmlSource:XML,objSource:XMLList):void
		{
			var i:int=0;
			var idValue:String;
			while(i<objSource.length())
			{
				if(objSource[i][_pidField].toString()==id)
				{
					var xml:XML=(objSource[i] as XML).copy();
					idValue=objSource[i][_idField].toString();
					xmlSource.appendChild(xml);
					delete objSource[i];
					searchItemForIDDown(idValue,xmlSource,objSource);
					i=-1;
				}
				i++;
			}
		}
		
		/**
		 * 添加Qpath表 
		 * @param item
		 * @return 
		 * 
		 */		
		public function addQItem(item:Object):Object
		{
			var obj:Object;
			if(item is XML && item.dataTable[0]!=null)
			{
				var add:Boolean=false;
				_addDataTableSource=(item.dataTable[0] as XML).children()[0];
				var xmlList:XMLList=_addDataTableSource.children();
				var iCount:int=xmlList.length();
				var i:int;
				if(this._dataTable.length)
				{
					for(i=0;i<iCount;i++)
					{
						for(var j:int=0;j<this._dataTable.length;j++)
						{
							if(xmlList[i]==_dataTable[j])
							{
								break;
							}
						}
						if(j==this._dataTable.length)
						{
							add=true;
							_dataTable.addItem(xmlList[i]);
						}
					}
				}
				else
				{
					for(i=0;i<iCount;i++)
					{
						add=true;
						_dataTable.addItem(xmlList[i]);
					}
				}
				
				if(add)
				{
					refreshDataTree();
				}
				obj=xTree.children();
			}
			return obj;
		}
		
		
		
		/**
		 * 重新生成tree结构 
		 * 
		 */		
		public function refreshDataTree():void
		{
			if(_dataTable.source.length()>0)
			{
				var dataSource:XMLList=_dataTable.source.copy();
				dataSource=XMLUnit.sortXML(dataSource,orderByField,desc);
				xTree=XML(<tree />);
				if(_idField!="" && _idField!= null && _pidField!="" && _pidField !=null &&
					 _rootValue!="" && _rootValue!=null && _labelField!="" && _labelField!=null){
					xmlToTreeNode(xTree,dataSource,_idField,_pidField,_rootValue,_labelField);
					super.source=xTree.children();
				}
				else if(_idField!="" && _idField!= null && _labelField!="" && _labelField!=null){
					var xList:XMLList=dataSource;
					xTree=new XML(<tree />);
					var iLen:int=xList.length();
					var treeNode:XML;
					for(var i:int=0;i<iLen;i++)
					{
						treeNode= new XML("<tree "+_labelField+"=\""+StrUnit.replaceRevert(xList[i][_labelField].toString())+"\" idValue=\""+ xList[i][_idField].toString() +"\" /> "); 
						EDIApplication.outputDebug("treeNode123: "+treeNode.toString());
						super.list.addItem(treeNode);
					}
				}
			}		
		}
		
		/**
		 * 根据行更新本节点的labelField; 
		 * @param item 
		 * 
		 */		
		public function updateTreeNodeForRow(item:Object):void
		{
			var idValue:String=item[_idField];
			var labelValue:String=item[_labelField];
			upDateTree(idValue,labelValue,xTree);
		}
		
		private function upDateTree(idValue:String,labelValue:String,value:XML):Boolean
		{
			var ret:Boolean=false;

			if(value["@idValue"]==idValue)
			{
				value[0]["@"+_labelField]=labelValue;
				ret=true;
			}
			else
			{
				var xmlList:XMLList=value.children();
				var iCount:int=xmlList.length();
				for(var i:int=0;i<iCount;i++)
				{
					ret=upDateTree(idValue,labelValue,xmlList[i]);
					if(ret)
					{
						break;
					}
				}
			}
			return ret;
		}
		
		/**
		 *  根据某节点Item生成该节点下的子树
		 * @param item
		 * @return 
		 * 
		 */		
		public function treeNodeChildQItem(item:Object):Object
		{
			var xmlSource:XML=new XML(<db />);
			
			if(item is XML && (item as XML).hasOwnProperty("@idValue"))
			{
				var id:String=(item as XML)["@idValue"];
				
				for(var j:int=0;j<this._dataTable.length;j++)
				{
					if(id==_dataTable[j][_idField].toString())
					{
						xmlSource.appendChild((_dataTable[j] as XML).copy());
						break;
					}
				}
				
				searchItemForIDDown(id,xmlSource,_dataTable.source.copy());
			}
			
			return new XML(<obj>
				<dataTable>{xmlSource}</dataTable>
			</obj>);
		}
	}
}